<template>
  <div>
    <div ref="bridge" style="display: none;"></div>
    <base-modal
      :title="title"
      :show.sync="visible"
      width="600px"
      :close-on-click-modal="false"
      @closed="closeModal"
    >
      <div class="batch-update-container">
        <div class="base-import-warn" v-if="mode === 1">
          {{$t('goods.component.downloadFirst')}}
          <a href="#" @click="downloadTemplate">{{$t('goods.component.importTemplate')}}</a>{{$t('goods.component.fillingText')}}
        </div>
        <div class="base-import-file">
          <p>{{ fileName }}</p>
          <el-button type="primary" @click="choose" :disabled="pending"
            >{{$t('common.base.chooseFile')}}</el-button
          >
          <input
            v-if="mode === 1"
            type="file"
            ref="file"
            @change="change"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          />
          <input
            v-else
            type="file"
            ref="file"
            @change="change"
            accept="application/zip,application/x-zip,application/x-zip-compressed"
          />
        </div>
        <div class="file-tip" v-if="mode === 2">
          <div>{{$t('goods.limit.uploadLimit', {num1: '100'})}}</div>
          <div>
            {{$t('goods.limit.nameLimit', {num1: '5'})}}<span>{{$t('goods.component.cover')}}</span>{{$t('goods.limit.noLimit')}}
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="handleImport" :loading="loading"
          >{{$t('common.base.import')}}</el-button
        >
      </div>
    </base-modal>
  </div>
</template>

<script>
import Uploader from '@src/util/uploader';
import Platform from '@src/util/platform.ts';
import { getRootWindow } from '@src/util/dom'

export default {
  props: {
    selectedIds: {
      type: Array,
      default: () => [],
    },
  },
  emits: ['reloadPage'],
  data() {
    return {
      visible: false,
      loading: false,
      pending: false,
      mode: 1,
      file: null,
      fileName: '',
      errors: [],
      templateUrl: '',
    };
  },
  computed: {
    title() {
      return this.mode === 1 ? this.$t('common.base.batchUpdate') : this.$t('goods.component.batchUpdateImg');
    },
  },
  methods: {
    closeModal() {
      this.file = null;
      this.fileName = '';
      this.errors = [];
    },
    choose() {
      this.$refs.file.value = null;
      this.$refs.file.click();
    },
    change(event) {
      const files = event.target.files;
      if (!files || files.length == 0) return;
      let file = files[0];

      this.errors = [];
      this.fileName = file.name;
      this.file = file;
    },
    open(mode = 1) {
      this.mode = mode;
      this.visible = true;
    },
    handleImport() {
      if (!this.file || !(this.file instanceof File)) {
        return Platform.alert(this.$t('common.placeholder.selectImportFile'));
      }

      this.$confirm(this.$t('part.components.partImport.text4'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
      })
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: this.$t('goods.tips.importing'),
          });
          let action = this.mode == 1 ? '/excels/serviceMall/update':'/files/uploadPictureCompressedPackage?module=SERVICE_MALL'
          this.pending = true;
          Uploader.upload(this.file, action, { validateStorage: false })
            .then(result => {
              if (result.status == 0) {
                Platform.alert(result?.message || this.$t('goods.tips.importSucceeded'));
                this.$emit('reloadPage');
                this.visible = false;
                const RootWindow = getRootWindow(window)
                RootWindow?.exportPopoverToggle(true)
              } else {
                Platform.alert(result?.message||this.$t('goods.tips.importFailed'));
              }
            })
            .catch(err => {
              console.error(err);
              Platform.alert(this.$t('goods.tips.importFailed'));
            })
            .finally(() => {
              this.pending = false;
              loading.close()
            });
        })
        .catch(err => {
          console.warn(err);
        })
    },
    async downloadTemplate(){
      const loading = this.$loading({
        lock: true,
        text: this.$t('goods.tips.downloading'),
      });
      this.$http.post('/api/linkc/outside/linkc/v3b/shop/commodity/exportBathUpdateTemplate', this.selectedIds, true, {responseType: 'blob'})
        .then(blob => {
          if(!blob) return this.$message.error(this.$t('goods.tips.downloadFailed'))
          let link = document.createElement('a');
          let url = URL.createObjectURL(blob);
          link.download = this.$t('goods.component.updateTemplate');
          link.href = url;
          this.$refs.bridge.appendChild(link);
          link.click();
          setTimeout(() => {
            URL.revokeObjectURL(url);
            this.$refs.bridge.removeChild(link);
          }, 150);
        })
        .catch(err =>{
          console.error(err)
          this.$message.error(this.$t('goods.tips.downloadFailed'))
        })
        .finally(() => {
          loading.close();
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.batch-update-container {
  padding: 20px;

  .base-import-warn {
    padding: 5px 10px;
    border-radius: 2px;
    background-color: #fdf6ec;
    color: #e6a23c;
    margin-bottom: 15px;

    a {
      cursor: pointer;
    }
  }

  .base-import-file {
    display: flex;
    flex-flow: row nowrap;
    margin-bottom: 15px;

    &:last-child {
      margin-bottom: 5px;
    }
    p {
      flex: 1;
      line-height: 24px;
      padding: 3px 6px;

      border: 1px solid #d5d5d5;
      background-color: #fff;
      border-right: none;
      margin: 0;
      border-radius: 2px 0 0 2px;
    }

    .el-button {
      border-radius: 0 2px 2px 0;
    }

    input[type='file'] {
      display: none;
    }
  }

  .file-tip {
    font-size: 13px;
    color: #8c8c8c;

    span {
      color: #ff4d4f;
    }
  }
}
</style>
